/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.ap.entity.*;
import com.jeeplus.modules.ap.service.AdvanceService;
import com.jeeplus.modules.ap.service.BillAddService;
import com.jeeplus.modules.ap.service.RecelService;
import com.jeeplus.modules.ap.service.SlService;
import com.jeeplus.modules.fee.entity.FeeZzsl;
import com.jeeplus.modules.fee.service.FeeZzslService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.infor.service.TakeAddressService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.mapper.AdditionalChargesMapper;
import com.jeeplus.modules.tms.service.NewBillService;
import com.jeeplus.modules.tms.service.NewPlanningService;
import com.jeeplus.modules.tms.service.NewTransportService;
import com.jeeplus.modules.tms.util.FileUtil;
import com.jeeplus.modules.tms.util.PrintWayBill;
import com.jeeplus.modules.wms.entity.MaterialParticulars;
import com.jeeplus.modules.wms.entity.Outbound;
import com.jeeplus.modules.wms.entity.StorageInform;
import com.jeeplus.modules.wms.entity.Storehouse;
import com.jeeplus.modules.wms.mapper.MaterialParticularsMapper;
import com.jeeplus.modules.wms.mapper.StorehouseMapper;
import com.jeeplus.modules.wms.service.OutboundService;
import com.jeeplus.modules.wms.service.StorageInformService;
import com.jeeplus.modules.wms.util.CopyUtil;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.service.DispatchingService;

/**
 * 派车单Controller
 * @author 李超辉
 * @version 2019-04-29
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/dispatching")
public class DispatchingController extends BaseController {

	@Autowired
	private DispatchingService dispatchingService;
	@Autowired
	private NewTransportService newTransportService;
	@Autowired
	private NewBillService newBillService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private OutboundService outboundService;
	@Autowired
	private StorehouseMapper storehouseMapper;
	@Autowired
	private NewPlanningService newPlanningService;
	@Autowired
	private StorageInformService storageInformService;
	@Autowired
	private MaterialParticularsMapper materialParticularsMapper;
	@Autowired
	private AdvanceService advanceService;
	@Autowired
	private RecelService recelService;
	@Autowired
	private TakeAddressService takeAddressService;
	@Autowired
	private AdditionalChargesMapper additionalChargesMapper;
	@Autowired
	private BillAddService billAddService;
	@Autowired
	private SlService slService;
	@Autowired
	private FeeZzslService zzslService;
	@Autowired
	private JdbcTemplate jdbc;

	@ModelAttribute
	public Dispatching get(@RequestParam(required=false) String id) {
		Dispatching entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = dispatchingService.get(id);
		}
		if (entity == null){
			entity = new Dispatching();
		}
		return entity;
	}
	
	/**
	 * 派车单列表页面
	 */
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/dispatchingList";
	}

	/**
	 * 运费支出
	 */
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/tms/2/dispatchingList";
	}
	/**
	 * 运费支出
	 */
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/tms/3/dispatchingList";
	}

	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/tms/4/dispatchingList";
	}
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list4"})
	public String list4() {
		return "modules/tms/5/dispatchingList";
	}
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list5"})
	public String list6() {
		return "modules/tms/6/dispatchingList";
	}
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = {"list6"})
	public String list7() {
		return "modules/tms/7/dispatchingList";
	}
		/**
	 * 派车单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Dispatching dispatching, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			dispatching.setPro(pro);
		}
		Page<Dispatching> page = dispatchingService.findPage(new Page<Dispatching>(request, response), dispatching);
		return getBootstrapData(page);
	}
	/**
	 * 派车单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(Dispatching dispatching, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			dispatching.setPro(pro);
		}
		dispatching.setHt("1");
			Page<Dispatching> page = dispatchingService.findPage(new Page<Dispatching>(request, response), dispatching);
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(Dispatching dispatching, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			dispatching.setPro(pro);
		}
		dispatching.setHt("1");
		Page<Dispatching> page = dispatchingService.findPage(new Page<Dispatching>(request, response), dispatching);
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequiresPermissions("tms:dispatching:list")
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(Dispatching dispatching, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			dispatching.setPro(pro);
		}
		dispatching.setHt("1");
		Page<Dispatching> page = dispatchingService.findPage1(new Page<Dispatching>(request, response), dispatching);
		return getBootstrapData(page);
	}
	/**
	 * 调用打印页面
	 */
	@RequestMapping(value = "dayin")
	public String dayin(Dispatching dispatching,HttpServletRequest request,  Model model) throws Exception {

		//模版文件目录
		String templateFile = request.getSession().getServletContext().getRealPath("static/common/pdf/stenail/newHT.pdf");

		//要合并的pdf所在文件夹
		String folder = request.getSession().getServletContext().getRealPath("static/common/pdf/example/");
		//用于存放需要合并的pdf文件名
		List<String> filelist = new ArrayList<String>();
		//多条数据
			List<Map<String,Object>> list=jdbc.queryForList("SELECT a.lx ,sum(a.zcl/goods.proportion) as gross,SUM(a.weight)as weight, SUM(a.voulm)  as volume FROM tms_new_bill a LEFT JOIN infor_goods goods on goods.id=a.name  where a.pcdh='"+dispatching.getPcdh() +"' GROUP BY a.lx;");
			//时间戳命名要合并的pdf并加入list
			String filewei = "HT"+new Date().getTime() + ".pdf";
			//要合并的pdf目录
			String outFile = folder + "/"+filewei;
			File file = new File(outFile);
			if (!file.exists()) {
				try {
					file.createNewFile();
					System.out.println("创建成功!");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			updatePdfa(dispatching, list, templateFile, file);
			filelist.add(filewei);
			//}
		//合并后pdf所在文件夹
		String outPdfFileqian = request.getSession().getServletContext().getRealPath("static/common/pdf/print/");
		//合并后pdf文件目录
		String outPdfFile = outPdfFileqian+"/mergepdfbill"+new Date().getTime() + ".pdf";
		//合并pdf方法
		mergePdf(folder, outPdfFile,filelist);
//定时删除合并前的文件以及合并后的文件
		Timer timer = new Timer();//实例化Timer类
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					FileUtil.deleteFile(outPdfFile);
					for (int i = 0; i < filelist.size(); i++){
						FileUtil.deleteFile(folder + File.separator + filelist.get(i));
						System.out.println("删除文件成功");}

				} catch (Exception e) {

				} finally {
					this.cancel();
				}

			}
		}, 50000);//五万毫秒 50秒
		//将合并后的pdf目录传到jsp供读取
		request.setAttribute("outPdfFile",outPdfFile);
		return "modules/tms/print/pdfbill";
	}


	public void updatePdfa(Dispatching tmsWaybill,  List<Map<String,Object>> mapList, String templateFile, File file) throws Exception {

		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		String idd=tmsWaybill.getRemarks();
		String[] ids=idd.split(",");
		String id=ids[0];
		NewBill bill=newBillService.get(id);
		String hz="";
		String th="";
		for(String i:ids){
			NewBill bil=newBillService.get(i);
			if(!hz.contains(bil.getZydh())){
				hz+=bil.getZydh()+"  ";
			}
			if(!th.contains(bil.getThdh())){
				th+=bil.getThdh()+"  ";
			}
		}
		PdfReader reader = new PdfReader(templateFile); // 模版文件目录
		FileOutputStream fos = new FileOutputStream(file);

		PdfStamper ps = new PdfStamper(reader, fos); // 生成的输出流

		BaseFont bf = BaseFont.createFont("c:/WINDOWS/fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

		AcroFields s = ps.getAcroFields();

		//主表
		s.setFieldProperty("hth", "textfont", bf, null);
		s.setFieldProperty("tyr", "textfont", bf, null);
		s.setFieldProperty("tydh", "textfont", bf, null);
		s.setFieldProperty("cys", "textfont", bf, null);
		s.setFieldProperty("cyr", "textfont", bf, null);
		s.setFieldProperty("cyrdh", "textfont", bf, null);
		s.setFieldProperty("cphm", "textfont", bf, null);
		s.setFieldProperty("xszh", "textfont", bf, null);
		s.setFieldProperty("sj", "textfont", bf, null);
		s.setFieldProperty("sjdh", "textfont", bf, null);
		s.setFieldProperty("sfzh", "textfont", bf, null);
		s.setFieldProperty("jszh", "textfont", bf, null);
		s.setFieldProperty("shdw", "textfont", bf, null);
		s.setFieldProperty("shr", "textfont", bf, null);
		s.setFieldProperty("shdz", "textfont", bf, null);
		s.setFieldProperty("qyd", "textfont", bf, null);
		s.setFieldProperty("mdd", "textfont", bf, null);
    	s.setFieldProperty("hzdh", "textfont", bf, null);
		s.setFieldProperty("wch", "textfont", bf, null);
		s.setFieldProperty("qyn", "textfont", bf, null);
		s.setFieldProperty("qyy", "textfont", bf, null);
		s.setFieldProperty("qyr", "textfont", bf, null);
		s.setFieldProperty("hdn", "textfont", bf, null);
		s.setFieldProperty("hdy", "textfont", bf, null);
		s.setFieldProperty("hdr", "textfont", bf, null);
//		s.setFieldProperty("qiyunnian", "textfont", bf, null);
//		s.setFieldProperty("yundaonian", "textfont", bf, null);
//		s.setFieldProperty("huodaowan", "textfont", bf, null);
//		s.setFieldProperty("huodaoqian", "textfont", bf, null);
//		s.setFieldProperty("huodaobai", "textfont", bf, null);
//		s.setFieldProperty("huodaoshi", "textfont", bf, null);
//		s.setFieldProperty("huodaoge", "textfont", bf, null);
//		s.setFieldProperty("huodaoxiao", "textfont", bf, null);
//		s.setFieldProperty("zhuanghuowan", "textfont", bf, null);
//		s.setFieldProperty("zhuanghuoqian", "textfont", bf, null);
//		s.setFieldProperty("zhuanghuobai", "textfont", bf, null);
//		s.setFieldProperty("zhuanghuoshi", "textfont", bf, null);
//		s.setFieldProperty("zhuanghuoge", "textfont", bf, null);
//		s.setFieldProperty("zhuanghuoxiao", "textfont", bf, null);
//		s.setFieldProperty("huizhiwan", "textfont", bf, null);
//		s.setFieldProperty("huizhiqian", "textfont", bf, null);
//		s.setFieldProperty("huizhibai", "textfont", bf, null);
//		s.setFieldProperty("huizhige", "textfont", bf, null);
//		s.setFieldProperty("huizhixiao", "textfont", bf, null);
//		s.setFieldProperty("hejiwan", "textfont", bf, null);
//		s.setFieldProperty("hejiqian", "textfont", bf, null);
//		s.setFieldProperty("hejibai", "textfont", bf, null);
//		s.setFieldProperty("hejige", "textfont", bf, null);
//		s.setFieldProperty("hejixiao", "textfont", bf, null);
//		s.setFieldProperty("hejishi", "textfont", bf, null);
//		s.setFieldProperty("shoukuanren", "textfont", bf, null);
//		s.setFieldProperty("kaihuhang", "textfont", bf, null);
//		s.setFieldProperty("jiayoukahao", "textfont", bf, null);
//		s.setFieldProperty("kahao", "textfont", bf, null);
//		s.setFieldProperty("jiayoukajine", "textfont", bf, null);
//		s.setFieldProperty("tuoyunrenqian", "textfont", bf, null);
//		s.setFieldProperty("xianchang", "textfont", bf, null);
//		s.setFieldProperty("chengyunqian", "textfont", bf, null);
//		s.setFieldProperty("qiandingnian1", "textfont", bf, null);
//		s.setFieldProperty("qiandingyue1", "textfont", bf, null);
//		s.setFieldProperty("qiandingri1", "textfont", bf, null);
//		s.setFieldProperty("qiandingnian2", "textfont", bf, null);
//		s.setFieldProperty("qiandingri2", "textfont", bf, null);
//		s.setFieldProperty("qiandingyue2", "textfont", bf, null);
//		s.setFieldProperty("qiyunyue", "textfont", bf, null);
//		s.setFieldProperty("qiyunri", "textfont", bf, null);
//		s.setFieldProperty("yundaoyue", "textfont", bf, null);
//		s.setFieldProperty("yundaori", "textfont", bf, null);
for(int i=1;i<=4;i++){
	s.setFieldProperty("lx"+i, "textfont", bf, null);
	s.setFieldProperty("sl"+i, "textfont", bf, null);
	s.setFieldProperty("zl"+i, "textfont", bf, null);
	s.setFieldProperty("tj"+i, "textfont", bf, null);
	s.setFieldProperty("w"+i, "textfont", bf, null);
	s.setFieldProperty("q"+i, "textfont", bf, null);
	s.setFieldProperty("b"+i, "textfont", bf, null);
	s.setFieldProperty("s"+i, "textfont", bf, null);
	s.setFieldProperty("g"+i, "textfont", bf, null);
	s.setFieldProperty("xx"+i, "textfont", bf, null);
}

		//设置值（主表）
		s.setField("hth", tmsWaybill.getHth());
		s.setField("cys", tmsWaybill.getCys());
		s.setField("cyr", tmsWaybill.getCyslxr());
		s.setField("cyrdh", tmsWaybill.getCysdh());
		s.setField("cphm", tmsWaybill.getCph());
		s.setField("xszh", tmsWaybill.getXszh());
		s.setField("sj", tmsWaybill.getSjxm());
		s.setField("sjdh", tmsWaybill.getSjdh());
		s.setField("sfzh", tmsWaybill.getXszh());
		s.setField("jszh", tmsWaybill.getXszh());

		s.setField("shdw", bill.getShdw());
		s.setField("shr", bill.getQrr()+":"+bill.getQrrdh());
		s.setField("shdz", bill.getSite());
		s.setField("qyd", bill.getQyd().getName());
		s.setField("mdd", bill.getJsd().getName());
		s.setField("hzdh", hz+"/"+th);
		s.setField("wch",tmsWaybill.getWccyddh());

		Date date =bill.getLkthd();
		Date date1=bill.getYjdd();
		SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd");
		String d= myFmt2.format(date);
		String d1= myFmt2.format(date1);
		s.setField("qyn", d.substring(0,4));
		s.setField("qyy", d.substring(5,7));
		s.setField("qyr", d.substring(8,10));
		s.setField("hdn", d.substring(0,4));
		s.setField("hdy", d.substring(5,7));
		s.setField("hdr", d.substring(8,10));
		int w;
		int q;
		int b;
		int sh;
		int g;
		int a;
		if(tmsWaybill.getHdfk()!=null&&tmsWaybill.getHdfk().length()>0){
			a=Integer.parseInt(tmsWaybill.getHdfk());
			w=a/10000;
			q=a%10000/1000;
			b=a%1000/100;
			sh=a%100/10;
			g=a%10;
			s.setField("w1", getNumber(w));
			s.setField("q1", getNumber(q));
			s.setField("b1", getNumber(b));
			s.setField("s1", getNumber(sh));
			s.setField("g1", getNumber(g));
			s.setField("xx1", tmsWaybill.getHdfk());
		}
		if(tmsWaybill.getZhfk()!=null&&tmsWaybill.getZhfk().length()>0){
			a=Integer.parseInt(tmsWaybill.getZhfk());
			w=a/10000;
			q=a%10000/1000;
			b=a%1000/100;
			sh=a%100/10;
			g=a%10;
			s.setField("w2", getNumber(w));
			s.setField("q2", getNumber(q));
			s.setField("b2", getNumber(b));
			s.setField("s2", getNumber(sh));
			s.setField("g2", getNumber(g));
			s.setField("xx2", tmsWaybill.getZhfk());
		}
		if(tmsWaybill.getHzjs()!=null&&tmsWaybill.getHzjs().length()>0){
			a=Integer.parseInt(tmsWaybill.getHzjs());
			w=a/10000;
			q=a%10000/1000;
			b=a%1000/100;
			sh=a%100/10;
			g=a%10;
			s.setField("w3", getNumber(w));
			s.setField("q3", getNumber(q));
			s.setField("b3", getNumber(b));
			s.setField("s3", getNumber(sh));
			s.setField("g3", getNumber(g));
			s.setField("xx3", tmsWaybill.getHzjs());
		}
		if(tmsWaybill.getZyf()!=null&&tmsWaybill.getZyf().length()>0){
			a=Integer.parseInt(tmsWaybill.getZyf());
			w=a/10000;
			q=a%10000/1000;
			b=a%1000/100;
			sh=a%100/10;
			g=a%10;
			s.setField("w4", getNumber(w));
			s.setField("q4", getNumber(q));
			s.setField("b4", getNumber(b));
			s.setField("s4", getNumber(sh));
			s.setField("g4", getNumber(g));

			s.setField("xx4", tmsWaybill.getZyf());
		}

		//子表
		NumberFormat nf = NumberFormat.getInstance();
		for (int i =0; i< mapList.size(); i++) {
			int j=i+1;
			s.setField("lx"+j, (String) mapList.get(i).get("lx"));
			s.setField("sl"+j, mapList.get(i).get("gross")+"");
			s.setField("zl"+j,  nf.format(mapList.get(i).get("weight")));
			s.setField("tj"+j,  nf.format(mapList.get(i).get("volume")));
		}
		ps.setFormFlattening(true); // 这句不能少

		ps.close();
		reader.close();
		fos.close();
	}


	public  static  String getNumber(int n){
		if(n==0){return "零";}
		else if(n==1){return "壹";}
		else if(n==2){return "贰";}
		else if(n==3){return "叁";}
		else if(n==4){return "肆";}
		else if(n==5){return "伍";}
		else if(n==6){return "陆";}
		else if(n==7){return "柒";}
		else if(n==8){return "捌";}
		else {return "玖";}
	}
	/**
	 *
	 * @param folder       要合并文件的文件夹
	 * @param outPdfFile    合并后的文件名
	 * @param fileString    需要合并的pdf文件名集合
	 * @throws Exception
	 */
	public void mergePdf(String folder, String outPdfFile, List<String> fileString) throws Exception {
		PDFMergerUtility mergePdf = new PDFMergerUtility();
		List<String> filesInFolder = fileString;
		for (int i = 0; i < filesInFolder.size(); i++)
			mergePdf.addSource(folder + File.separator + filesInFolder.get(i));
		mergePdf.setDestinationFileName(outPdfFile);
		mergePdf.mergeDocuments();
	}

	/**
	 * 查看，增加，编辑派车单表单页面
	 */
	@RequiresPermissions(value={"tms:dispatching:view","tms:dispatching:add","tms:dispatching:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Dispatching dispatching,String i, Model model) {
		String[] ids=i.split(",");
		List<NewTransport> list=new ArrayList<>();
		for(String id:ids){
			list.add(newTransportService.get(id));
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String code=UserUtils.getUserAre()+sdf.format(new Date());
		Dispatching p=new Dispatching();
		p.setPcdh(code);
		List<Dispatching> l=dispatchingService.findList(p);
		if(l==null||l.size()<1){
			dispatching.setPcdh(code+"001"+"PC");
		}else{
			if(l.size()/10==0){
				dispatching.setPcdh(code+"00"+(l.size()+1)+"PC");
			}else
			if(l.size()/100==0){
				dispatching.setPcdh(code+"0"+(l.size()+1)+"PC");
			}else{dispatching.setPcdh(code+(l.size()+1)+"PC");}

		}
		Staff s=new Staff();
		s.setProjectName(UserUtils.getUseroffice());
		List<Staff> ml=staffService.findList(s);
		for(Staff staff:ml){
			staff=staffService.get(staff.getId());
			if(staff.getPosition().getName().contains("调度")){
				dispatching.setDdry(staff);
			}
		}
		dispatching.setJhl(i);
		model.addAttribute("list", list);
		model.addAttribute("dispatching", dispatching);
		return "modules/tms/dispatchingForm";
	}


	/**
	 * 查看，增加，编辑派车单表单页面
	 */
	@RequiresPermissions(value={"tms:dispatching:view","tms:dispatching:add","tms:dispatching:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(Dispatching dispatching, Model model) {
		String[] ids=dispatching.getRemarks().split(",");
		List<NewBill> list=new ArrayList<>();
		for(String id:ids){
			list.add(newBillService.get(id));
		}
		String zch=dispatching.getPcdh().replace("PC","ZC");
		dispatching.setZcxyh(zch);
		model.addAttribute("list", list);
		model.addAttribute("dispatching", dispatching);
		return "modules/tms/1/dispatchingForm";
	}

	/**
	 * 查看，增加，编辑派车单表单页面
	 */
	@RequiresPermissions(value={"tms:dispatching:view","tms:dispatching:add","tms:dispatching:edit"},logical=Logical.OR)
	@RequestMapping(value = "ck")
	public String ck(String code, Model model) {
		Dispatching dispatching=dispatchingService.findUniqueByProperty("hth",code);
		dispatching=dispatchingService.get(dispatching.getId());
		String[] ids=dispatching.getRemarks().split(",");
		List<NewBill> list=new ArrayList<>();
		for(String id:ids){
			list.add(newBillService.get(id));
		}
		model.addAttribute("list", list);
		model.addAttribute("dispatching", dispatching);
		return "modules/tms/1/dispatchingForm";
	}

	/**
	 * 保存派车单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:dispatching:add","tms:dispatching:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Dispatching dispatching,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, dispatching)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		NumberFormat nf = NumberFormat.getInstance();
		String[] ids=dispatching.getJhl().split(",");
		String pp="";
		String bill="";
		int zjs=0;
		double zzl=0.0;
		for(String id:ids){
            String pcl=request.getParameter(id);
            pp+=pcl+",";
            zjs+=Integer.parseInt(pcl);
			NewTransport t=newTransportService.get(id);
			String ypc=t.getPcl();
			double pc=Double.parseDouble(pcl)+Double.parseDouble(ypc);
			Goods g=goodsService.get(t.getName().getId());
			 zzl+=Integer.parseInt(pcl)*Double.parseDouble(g.getGrossWeight());
			double yf=pc*Double.parseDouble(g.getGrossWeight());
			double yftj=pc*Double.parseDouble(g.getVolume());
			double wf=Double.parseDouble(t.getWeight())-yf;
			double wftj=Double.parseDouble(t.getVoulm())-yftj;

			t.setPcl(nf.format(pc).replaceAll(",",""));
			t.setYf(nf.format(yf).replaceAll(",",""));
			t.setWf(nf.format(wf).replaceAll(",",""));
			t.setWftj(nf.format(wftj).replaceAll(",",""));
			double jh=Double.parseDouble(t.getGross());
			t.setStatus("已配载");
			if(pc<jh){
				t.setJhstatus("部分计划");
			}else{
				t.setJhstatus("计划完成");
			}
        newTransportService.save(t);
			NewBill b=new NewBill();
			CopyUtil.Copy(b,t,false);
			CopyUtil.Copy(b,dispatching,false);
			b.setBx("未投保");
			b.setStatus("已配载");
			b.setZydh(t.getZydh());
			b.setThdh(t.getThdh());
			b.setQyd(t.getQyd());
			b.setJsd(t.getJsd());
			b.setPort(t.getId());
			b.setZylx(t.getZylx());
			b.setDzs(t.getDzs());
			b.setPcl(pcl);
			b.setZcl(pcl);
			NewBill bi=new NewBill();
			bi.setCode(t.getWtdh());
			bi.setPro(t.getPro());
			List<NewBill> l=newBillService.findList(bi);
			if(l==null||l.size()<1){
				b.setYdh(t.getWtdh()+"-1");
			}else{b.setYdh(t.getWtdh()+"-"+(l.size()+1));}
			double pczl=Double.parseDouble(pcl)*Double.parseDouble(g.getGrossWeight());
			double pctj=Double.parseDouble(pcl)*Double.parseDouble(g.getVolume());
			b.setWeight(nf.format(pczl).replaceAll(",",""));
			b.setVoulm(nf.format(pctj).replaceAll(",",""));
			b.setPro(t.getPro());
			newBillService.save(b);
			bill+=b.getId()+",";
		}
		dispatching.setPcl(pp);
		dispatching.setZjs(zjs+"");
		dispatching.setZzl(nf.format(zzl).replaceAll(",",""));
		dispatching.setRemarks(bill);
		dispatching.setPro(UserUtils.getUseroffice());
		dispatching.setStatus("已配载");
		dispatching.setHt("0");
		dispatchingService.save(dispatching);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存派车单成功");
		return j;
	}


	/**
	 * 保存派车单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:dispatching:add","tms:dispatching:edit"},logical=Logical.OR)
	@RequestMapping(value = "save1")
	public AjaxJson save1(Dispatching dispatching,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
//		if (!beanValidator(model, dispatching)){
//			j.setSuccess(false);
//			j.setMsg("非法参数！");
//			return j;
//		}

		dispatching.setStatus("已装车");
		//新建或者编辑保存
		String[] bills=dispatching.getRemarks().split(",");
		double zl=0.0;
		int js=0;
		NumberFormat nf = NumberFormat.getInstance();
		for(String bill:bills){
			NewBill b=newBillService.get(bill);
			String zcl=request.getParameter(bill);
			String w=goodsService.get(b.getName().getId()).getGrossWeight();
			String v=goodsService.get(b.getName().getId()).getVolume();
			double z=Double.parseDouble(zcl)*Double.parseDouble(w);
			double vo=Double.parseDouble(zcl)*Double.parseDouble(v);
			b.setZcl(zcl);
			b.setWeight(nf.format(z).replaceAll(",",""));
			b.setVoulm(nf.format(vo).replaceAll(",",""));
			newBillService.save(b);
			zl+=z;
			int zc=Integer.parseInt(zcl);
			js+=zc;
			String pcl=b.getPcl();
			int pc=Integer.parseInt(pcl);
			if(pc>zc){
             NewTransport p=newTransportService.get(b.getPort());
             int jhpc=Integer.parseInt(p.getPcl());
             int npc=jhpc-(pc-zc);
             p.setPcl(npc+"");
             double yf=npc*Double.parseDouble(w);
             double yftj=npc*Double.parseDouble(v);
             p.setYf(nf.format(yf).replaceAll(",",""));
             double wf=Double.parseDouble(p.getWeight())-yf;
             p.setWf(nf.format(wf).replaceAll(",",""));
             double wftj=Double.parseDouble(p.getVoulm())-yftj;
             p.setWftj(nf.format(wftj).replaceAll(",",""));
             if(wf==0.0){
             	p.setJhstatus("未计划");
			 }else{
				 p.setJhstatus("部分计划");
			 }
			 newTransportService.save(p);
			}
		}
		dispatching.setZjs(js+"");
		dispatching.setZzl(nf.format(zl).replaceAll(",",""));
		for(String bill:bills){
			NewBill b=newBillService.get(bill);
			double zhfkxj=Double.parseDouble(dispatching.getZhfkxj())*Double.parseDouble(b.getWeight())/zl;
			double zhfkyk=Double.parseDouble(dispatching.getZhfkyk())*Double.parseDouble(b.getWeight())/zl;
			double zhfk=zhfkxj+zhfkyk;
			double hdfkxj=Double.parseDouble(dispatching.getHdfkxj())*Double.parseDouble(b.getWeight())/zl;
			double hdfkyk=Double.parseDouble(dispatching.getHdfkyk())*Double.parseDouble(b.getWeight())/zl;
            double hdfk=hdfkxj+hdfkyk;
			double hzfkxj=Double.parseDouble(dispatching.getHzfkxj())*Double.parseDouble(b.getWeight())/zl;
			double hzfkyk=Double.parseDouble(dispatching.getHzfkyk())*Double.parseDouble(b.getWeight())/zl;
            double hzjs=hzfkxj+hzfkyk;
			double zxj=zhfkxj+hdfkxj+hzfkxj;
			double zyk=zhfkyk+hdfkyk+hzfkyk;
			double zyf=zhfk+hdfk+hzjs;
			b.setZyf(nf.format(zyf).replaceAll(",",""));
			b.setZxj(nf.format(zxj).replaceAll(",",""));
			b.setZyk(nf.format(zyk).replaceAll(",",""));
			b.setZhfk(nf.format(zhfk).replaceAll(",",""));
			b.setYkzh(nf.format(zhfkyk).replaceAll(",",""));
			b.setXjzh(nf.format(zhfkxj).replaceAll(",",""));
			b.setHdfk(nf.format(hdfk).replaceAll(",",""));
			b.setHdfkyk(nf.format(hdfkyk).replaceAll(",",""));
			b.setHdfkxj(nf.format(hdfkxj).replaceAll(",",""));
			b.setHzjs(nf.format(hzjs).replaceAll(",",""));
			b.setHzfkyk(nf.format(hzfkyk).replaceAll(",",""));
			b.setHzfkxj(nf.format(hzfkxj).replaceAll(",",""));
			b.setWccyddh(dispatching.getWccyddh());
			b.setStatus("已装车");
			b.setFktype(dispatching.getZffs());
			newBillService.save(b);

		}
		dispatching.setWf(dispatching.getZyf());
		dispatching.setWfxj(dispatching.getZxj());
		dispatching.setWfyk(dispatching.getZyk());
		dispatching.setYf("0");
		dispatching.setYfxj("0");
		dispatching.setYfyk("0");
		dispatchingService.save(dispatching);
		j.setSuccess(true);
		j.setMsg("保存派车单成功");
		return j;
	}

	/**
	 * 删除派车单
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatching:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Dispatching dispatching, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		dispatchingService.delete(dispatching);
		j.setMsg("删除派车单成功");
		return j;
	}
	/**
	 * 预付款确认
	 */
	@ResponseBody
	@RequestMapping(value = "yfk")
	public AjaxJson yfk(Dispatching d, RedirectAttributes redirectAttributes) {
		NumberFormat nf = NumberFormat.getInstance();
		AjaxJson j = new AjaxJson();
		Advance a=new Advance();
		a.setStatus("已入账");
		a.setDate(d.getHtdate());
		a.setRz(new Date());
		a.setFkdate(new Date());
		a.setCode(d.getHth());
		a.setZccode(d.getZcxyh());
		a.setPerson(d.getCys());
		a.setCard(d.getCph());
		a.setPhone(d.getSjdh());
		a.setMoney(d.getZhfkxj());
		a.setOil(d.getZhfkyk());
		a.setNumber(d.getYkkh());
		a.setBill(d.getId());
		a.setPro(d.getPro());
        advanceService.save(a);
        String yf=d.getYf();
		String yfxj=d.getYfxj();
		String yfyk=d.getYfyk();
		String wf=d.getWf();
		String wfxj=d.getWfxj();
		String wfyk=d.getWfyk();
		String fk=d.getZhfk();
		String fkxj=d.getZhfkxj();
		String fkyk=d.getZhfkyk();
		double yf1=Double.parseDouble(yf)+Double.parseDouble(fk);
		double yfxj1=Double.parseDouble(yfxj)+Double.parseDouble(fkxj);
		double yfyk1=Double.parseDouble(yfyk)+Double.parseDouble(fkyk);
		double wf1=Double.parseDouble(wf)-Double.parseDouble(fk);
		double wfxj1=Double.parseDouble(wfxj)-Double.parseDouble(fkxj);
		double wfyk1=Double.parseDouble(wfyk)-Double.parseDouble(fkyk);
		d.setYf(nf.format(yf1).replaceAll(",",""));
		d.setYfxj(nf.format(yfxj1).replaceAll(",",""));
		d.setYfyk(nf.format(yfyk1).replaceAll(",",""));
		d.setWf(nf.format(wf1).replaceAll(",",""));
		d.setWfxj(nf.format(wfxj1).replaceAll(",",""));
		d.setWfyk(nf.format(wfyk1).replaceAll(",",""));
        d.setYfk("已支付");
		dispatchingService.save(d);
		j.setMsg("预付款确认成功");
		return j;
	}


	@ResponseBody
	@RequestMapping(value = "hzfk")
	public AjaxJson hzfk(Dispatching d,String yk,String xj,String number,String hdyk,String hdxj,String number1,String sm) throws Exception {
		AjaxJson ajaxJson=new AjaxJson();
			d.setHz("预处理");
			dispatchingService.save(d);
			String b=d.getRemarks();
			Recel a=new Recel();
			a.setNum(d.getZjs());
			a.setWeight(d.getZzl());
			a.setStart("");
			a.setNumber(number);
			a.setJsdate(new Date());
			a.setDate(d.getHtdate());
			a.setCode(d.getHth());
			a.setZccode(d.getZcxyh());
			a.setPerson(d.getSkr());
			a.setCard(d.getCph());
			a.setZcje(d.getZcfy());
			a.setDriver(d.getSjxm());
			a.setSfhd((Double.parseDouble(hdyk)+Double.parseDouble(hdxj))+"");
		    a.setHzxy((Double.parseDouble(yk)+Double.parseDouble(xj))+"");
			a.setBill(d.getId());
			a.setStatus("已入账");
			a.setRz(new Date());
			a.setReceipt(d.getPcdh());
			a.setPhone(d.getSjdh());
			a.setArrive("");
			a.setHdht(d.getHdfk());
			a.setHzht(d.getHzjs());
			a.setMoney(xj);
			a.setOil(yk);
			a.setSfhdxj(hdxj);
			a.setSfhdyk(hdyk);
			a.setHdnumber(number1);
			double sf=Double.parseDouble(hdxj)+Double.parseDouble(hdyk)+Double.parseDouble(yk)+Double.parseDouble(xj);
			a.setSfzje(sf+"");
			a.setRemarks(sm);
			a.setPro(d.getPro());
			a.setDelFlag("1");
			NumberFormat nf = NumberFormat.getInstance();
			double htzje=Double.parseDouble(d.getHdfk())+Double.parseDouble(d.getHzjs());
			double zj=sf-htzje;
			a.setZj(nf.format(zj).replaceAll(",",""));
			a.setHtzje(nf.format(htzje).replaceAll(",",""));
			recelService.save(a);
		ajaxJson.setMsg("回执付款成功");
		return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "hzqd")
	public AjaxJson hzqd(Dispatching d){
		AjaxJson ajaxJson=new AjaxJson();
		Recel a=recelService.findUniqueByProperty("bill",d.getId());
		a.setDelFlag("0");
		recelService.save(a);
		NumberFormat nf = NumberFormat.getInstance();
//		Yue yue=yueService.findUniqueByProperty("pro",UserUtils.getUseroffice());
//		yue.setXj(nf.format(Double.parseDouble(yue.getXj())-Double.parseDouble(a.getSfhd())-Double.parseDouble(a.getMoney())).replaceAll(",",""));
//		yue.setYk(nf.format(Double.parseDouble(yue.getYk())-Double.parseDouble(a.getOil())).replaceAll(",",""));
//		yue.setZje(nf.format(Double.parseDouble(yue.getZje())-Double.parseDouble(a.getSfhd())-Double.parseDouble(a.getMoney())-Double.parseDouble(a.getOil())).replaceAll(",",""));
//		yueService.save(yue);
//		TmsWaybill t=tmsWaybillService.get(i);
		String yf=d.getYf();
		String yfxj=d.getYfxj();
		String yfyk=d.getYfyk();
		String wf=d.getWf();
		String wfxj=d.getWfxj();
		String wfyk=d.getWfyk();
		String hdfk=d.getHdfk();
		String hdfkxj=d.getHdfkxj();
		String hdfkyk=d.getHdfkyk();
		String hzfk=d.getHzjs();
		String hzfkxj=d.getHzfkxj();
		String hzfkyk=d.getHzfkyk();
		double yf1=Double.parseDouble(yf)+Double.parseDouble(hdfk)+Double.parseDouble(hzfk);
		double yfxj1=Double.parseDouble(yfxj)+Double.parseDouble(hdfkxj)+Double.parseDouble(hzfkxj);
		double yfyk1=Double.parseDouble(yfyk)+Double.parseDouble(hdfkyk)+Double.parseDouble(hzfkyk);
		double wf1=Double.parseDouble(wf)-Double.parseDouble(hdfk)-Double.parseDouble(hzfk);
		double wfxj1=Double.parseDouble(wfxj)-Double.parseDouble(hdfkxj)-Double.parseDouble(hzfkxj);
		double wfyk1=Double.parseDouble(wfyk)-Double.parseDouble(hdfkyk)-Double.parseDouble(hzfkyk);
		d.setYf(nf.format(yf1).replaceAll(",",""));
		d.setYfxj(nf.format(yfxj1).replaceAll(",",""));
		d.setYfyk(nf.format(yfyk1).replaceAll(",",""));
		d.setWf(nf.format(wf1).replaceAll(",",""));
		d.setWfxj(nf.format(wfxj1).replaceAll(",",""));
		d.setWfyk(nf.format(wfyk1).replaceAll(",",""));
		d.setHz("已支付");
		dispatchingService.save(d);
		return ajaxJson;
	}
	@ResponseBody
	@RequestMapping(value = "hzqx")
	public AjaxJson hzqx(Dispatching d){
		AjaxJson ajaxJson=new AjaxJson();
		Recel a=recelService.findUniqueByProperty("bill",d.getId());
		recelService.delete(a);
		d.setHz("未支付");
		dispatchingService.save(d);
		return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "qxpz")
	public AjaxJson qxpz(Dispatching d){
		AjaxJson ajaxJson=new AjaxJson();
		if(!d.getStatus().equals("已配载")){
			Outbound o=new Outbound();
			o.setPcd(d.getId());
			List<Outbound> list=outboundService.findList(o);
			for(Outbound od:list){
				if(!od.getStatus().equals("已创建")){
					ajaxJson.setSuccess(false);
					ajaxJson.setMsg("仓库已经出库，请联系仓区取消出库后操作！");
					return ajaxJson;
				}
			}
			outboundService.deleteAll(list);

		}
		List<AdditionalCharges> cs=d.getAdditionalChargesList();

			for(AdditionalCharges cc:cs){
				additionalChargesMapper.delete(cc);
			}


		NumberFormat nf = NumberFormat.getInstance();
		String[] bi=d.getRemarks().split(",");
		for(String id:bi){
			NewBill bill=newBillService.get(id);
			NewTransport port=newTransportService.get(bill.getPort());
			String pcl=port.getPcl();
			Goods g=goodsService.get(port.getName().getId());
			String wei=g.getGrossWeight();
			int npc=Integer.parseInt(pcl)-Integer.parseInt(bill.getZcl());
			double yfzl=Double.parseDouble(wei)*npc;
			double wfzl=Double.parseDouble(port.getWeight())-yfzl;
			double wftj=Double.parseDouble(port.getWftj())+Double.parseDouble(bill.getVoulm());
			port.setPcl(npc+"");
			port.setWftj(nf.format(wftj).replaceAll(",",""));
			port.setWf(nf.format(wfzl).replaceAll(",",""));
			port.setYf(nf.format(yfzl).replaceAll(",",""));
			if(npc==0){
				port.setStatus("已创建");
				port.setJhstatus("未计划");
			}else{
				port.setJhstatus("部分计划");
			}
			newTransportService.save(port);
			newBillService.delete(bill);
		}

		dispatchingService.delete(d);
		return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "qxck")
	public AjaxJson qxck(Dispatching d){
		AjaxJson ajaxJson=new AjaxJson();
			Outbound o=new Outbound();
			o.setPcd(d.getId());
			List<Outbound> list=outboundService.findList(o);
			for(Outbound od:list){
				if(!od.getStatus().equals("已创建")){
					ajaxJson.setSuccess(false);
					ajaxJson.setMsg("仓库已经出库，请联系仓区取消出库后操作！");
					return ajaxJson;
				}
			}
			outboundService.deleteAll(list);
			d.setStatus("已配载");
		dispatchingService.save(d);
		return ajaxJson;
	}

	@ResponseBody
	@RequestMapping(value = "qxht")
	public AjaxJson qxht(Dispatching d){
		AjaxJson ajaxJson=new AjaxJson();
		Recel r=recelService.findUniqueByProperty("bill",d.getId());
		Advance a=advanceService.findUniqueByProperty("bill",d.getId());
		BillAdd add=billAddService.findUniqueByProperty("pid",d.getId());
		recelService.delete(r);
		advanceService.delete(a);
		billAddService.delete(add);
		d.setHz("未支付");
		d.setYfk("未支付");
		d.setHt("0");
		d.setStatus("已装车");
		dispatchingService.save(d);
		return ajaxJson;
	}
	/**
	 * 仓库列表
	 */
	@RequestMapping(value = "cklist")
	@ResponseBody
	public String cklist(Dispatching dispatching, Model model) {
		TakeAddress t=new TakeAddress();
		t.setPro(UserUtils.getUseroffice());
		List<TakeAddress> list=takeAddressService.findList(t);

		Gson g=new Gson();
		return g.toJson(list).toString();
	}

	/**
	 * 生成出库单
	 */
	@ResponseBody
	@RequestMapping(value = "ckd")
	public String ckd(Dispatching dispatching,String  i, RedirectAttributes redirectAttributes) {
		dispatching.setStatus("已生成出库单");
		dispatchingService.save(dispatching);
		String[] bills=dispatching.getRemarks().split(",");
		List<NewBill> list2=new ArrayList<>();
		List<List<NewBill>> list1=new ArrayList<>();
		String zyh="";
		for(String id:bills){
			NewBill b=newBillService.get(id);
			if(!zyh.contains(b.getZydh())){
				zyh+=b.getZydh()+",";
			}
			list2.add(b);
		}
		String[] zy=zyh.split(",");
		for(String z:zy){
			List<NewBill> l=new ArrayList<>();
			for(NewBill bill:list2){
				if(bill.getZydh().equals(z)&bill.getDeop().getId().equals(i)){
					l.add(bill);
				}
			}
			list1.add(l);
		}

		for(List<NewBill> list:list1){
			if(list==null||list.size()<1){continue;}
			NewBill bi=list.get(0);
			Outbound o=new Outbound();
			o.setStatus("已创建");
			o.setPcd(dispatching.getId());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			Outbound ou=new Outbound();
			ou.setCode(code);
			List<Outbound> ll=outboundService.findList(ou);
			if(ll==null||ll.size()<1){
				o.setCode(code+"001"+"CK");
			}else{
				if(ll.size()/10==0){
					o.setCode(code+"00"+(ll.size()+1)+"CK");
				}else
				if(ll.size()/100==0){
					o.setCode(code+"0"+(ll.size()+1)+"CK");
				}else{o.setCode(code+(ll.size()+1)+"CK");}

			}
			o.setShipmentNumbers(bi.getZydh());
			o.setSite(bi.getSite());
			o.setLogisticsName(bi.getCys());
			o.setLogisticsPerson(bi.getCyslxr());
			o.setLogisticsPhone(bi.getCysdh());
			o.setDriverName(bi.getSjxm());
			o.setDriverPhone(bi.getSjdh());
			o.setPlateNumber(bi.getCph());
			o.setUnitName(bi.getShdw());
			o.setUnitConfirmor(bi.getQrr());
			o.setPhone(bi.getQrrdh());
			o.setArriveProvince(bi.getDzs());
			o.setArriveCity(bi.getDzdcs());
			o.setDistance(bi.getHtlc());
			o.setTransitLines(bi.getYsxl());
			o.setProjectName(bi.getPro());
			o.setDate(bi.getDate());
			o.setDeliveryTime(bi.getFhdate());
			o.setArrivalTime(bi.getDhdate());
			o.setEntrustNumber(bi.getPcdh());
			if("销售订单".equals(bi.getType().trim())){
				o.setType("销售出库");
			}
			if("调拨订单".equals(bi.getType().trim())){
				o.setType("调拨出库");
			}
			o.setWorkType(bi.getZylx());
			outboundService.save(o);
			int zjs=0;
			double zmz=0.0;
			double ztj=0.0;
			for(NewBill nb:list){
				Storehouse s=new Storehouse();
				s.setOutbound(o);
				s.setStatus("未拣货");
				s.setBill(nb.getId());
				s.setName(nb.getName());
				s.setPro(nb.getPro());
				s.setNumber(nb.getThdh());
				s.setCode(nb.getCode());
				String pcl=nb.getPcl();
				Goods g=goodsService.get(nb.getName().getId());
				String weight=g.getGrossWeight();
				String volm=g.getVolume();
				zmz+=Integer.parseInt(pcl)*Double.parseDouble(weight);
				ztj+=Integer.parseInt(pcl)*Double.parseDouble(volm);
				zjs+=Integer.parseInt(pcl);
				s.setOrderNumber(pcl);
				s.setUnit(nb.getUnit());
				String lx=nb.getLx();
				s.setPacking(lx);
				s.setId(UUID.randomUUID().toString().replaceAll("-",""));
				storehouseMapper.insert(s);
				nb.setStatus("已生成出库单");
				newBillService.save(nb);
			}
			o.setAmount(zjs+"");
			o.setGrossWeight(zmz+"");
			o.setVolume(ztj+"");
			outboundService.save(o);
		}
	return "";
	}
	/**
	 * 生成合同
	 */
	@ResponseBody
	@RequestMapping(value = "scht")
	public AjaxJson scht(Dispatching dispatching, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		dispatching.setStatus("已生成合同");
		dispatching.setHt("1");
		dispatching.setHtdate(new Date());
		dispatching.setYfk("未支付");
		dispatching.setHz("未支付");
		dispatching.setHth(dispatching.getPcdh().replaceAll("PC","HT"));
		dispatchingService.save(dispatching);
		String[] ids=dispatching.getRemarks().split(",");
		NumberFormat nf = NumberFormat.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		for(String id:ids){
			NewBill n=newBillService.get(id);
			n.setStatus("已生成合同");
			n.setHt("1");
			n.setHth(dispatching.getHth());

			newBillService.save(n);
			NewBill bi=new NewBill();
			bi.setPort(n.getPort());
			List<NewBill> list=newBillService.findList(bi);
			boolean bol=true;
			for(NewBill bill:list){
				if(!bill.getHt().equals("1")){
                  bol=false;
				}
			}
			if(bol){
				NewTransport t=newTransportService.get(n.getPort());
				if(t.getJhstatus().equals("计划完成")){
					NewPlanning p=newPlanningService.get(t.getPlanning());
					p.setJf("满足");
					newPlanningService.save(p);
				}
			}

		}
		List<AdditionalCharges> charges=dispatching.getAdditionalChargesList();
		Double xxf=0.0;
		Double bxf=0.0;
		Double qtsr=0.0;
		Double fhp=0.0;
		Double zxf=0.0;
		Double qtzc=0.0;
		Double fhpsr=0.0;
		for(AdditionalCharges t1:charges){
			t1=additionalChargesMapper.get(t1.getId());
			if(t1.getBalanceType().contains("防护用品支出")){
				fhp+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("防护用品收入")){
				fhpsr+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("装卸费支出")){
				zxf+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("其他支出")){
				qtzc+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("信息费收入")){
				xxf+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("保险费收入")){
				bxf+=Double.parseDouble(t1.getMoney());
			}
			if(t1.getBalanceType().contains("其他收入")){
				qtsr+=Double.parseDouble(t1.getMoney());
			}
		}

		BillAdd add=new BillAdd();
		add.setPro(dispatching.getPro());
		add.setBxfsr(nf.format(bxf).replaceAll(",",""));
		add.setXxfsr(nf.format(xxf).replaceAll(",",""));
		add.setFhpsr(nf.format(fhpsr).replaceAll(",",""));
		add.setQtsr(nf.format(qtsr).replaceAll(",",""));
		add.setZch(dispatching.getZcxyh());
		add.setHth(dispatching.getHth());
		add.setFhpzc(nf.format(fhp).replaceAll(",",""));
		add.setZxfzc(nf.format(zxf).replaceAll(",",""));
		add.setQtzc(nf.format(qtzc).replaceAll(",",""));
		add.setPid(dispatching.getId());
		add.setPcdh(dispatching.getPcdh());
		add.setDate(new Date());
		add.setStatus("已入账");
		add.setRz(new Date());
		billAddService.save(add);
		j.setMsg("合同生成成功");
		return j;
	}


@ResponseBody
@RequestMapping("detail")
	public  List<NewBill> detils(Dispatching d){
		String[] ids=d.getRemarks().split(",");
		List<NewBill> bills=new ArrayList<>();
		for(String id:ids){
			NewBill bil=newBillService.get(id);
			bills.add(bil);
		}
		return bills;
	}
	/**
	 * 发车
	 */
	@ResponseBody
	@RequestMapping(value = "fc")
	public AjaxJson fc(Dispatching dispatching,String dd,String lk,String yjdd, RedirectAttributes redirectAttributes) throws ParseException {
		AjaxJson j = new AjaxJson();
		dispatching.setStatus("已发车");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00");
		dispatchingService.save(dispatching);
		String[] ids=dispatching.getRemarks().split(",");
		List<NewBill> list=new ArrayList<>();
		List<List<NewBill>> list1=new ArrayList<>();
		String zyh="";
		NumberFormat nf = NumberFormat.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		for(String id:ids){
			NewBill n=newBillService.get(id);
			n.setStatus("在途");
			n.setDthd(sdf.parse(dd));
			n.setYjdd(sdf.parse(yjdd));
			n.setLkthd(sdf.parse(lk));

			newBillService.save(n);
			if(n.getType().equals("调拨订单")){
				if(!zyh.contains(n.getZydh())){
					zyh+=n.getZydh()+",";
				}
				list.add(n);
			}
		}
		if(!zyh.equals("")){
		String[] zy=zyh.split(",");
		for(String z:zy){
			List<NewBill> l=new ArrayList<>();
			for(NewBill bill:list){
				if(bill.getZydh().equals(z)){
					l.add(bill);
				}}
			list1.add(l);
		}
		for(List<NewBill> l:list1){
			StorageInform s=new StorageInform();
            NewBill b=l.get(0);
			SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
			String co=UserUtils.getUserAre()+sd.format(new Date());
			StorageInform st=new StorageInform();
			st.setStorageNumber(co);
			List<StorageInform> li=storageInformService.findList(st);
			if(li==null||li.size()<1){
				s.setStorageNumber(co+"001"+"RK");
			}else{
				if(li.size()/10==0){
					s.setStorageNumber(co+"00"+(li.size()+1)+"RK");
				}else
				if(li.size()/100==0){
					s.setStorageNumber(co+"0"+(li.size()+1)+"RK");
				}else{s.setStorageNumber(co+(li.size()+1)+"RK");}

			}
            s.setProjectName(b.getShdw());
            s.setShippingNumber(b.getZydh());
            s.setState("已创建");
            s.setStorageType("调拨入库");
            s.setExpectDate(b.getYjdd());
            s.setProviderName(b.getCys());
            s.setProductionPlace(b.getQyd().getName());
            s.setName(b.getCyslxr());
            s.setPhone(b.getCysdh());
            s.setLogisticsBumber(b.getHth());
            s.setNumber(b.getCph());
            s.setDriverName(b.getSjxm());
            s.setDriverPhone(b.getSjdh());
            s.setType(b.getZylx());
            s.setQuantitiesReceived("0");
            storageInformService.save(s);
			int zjs=0;
			double zmz=0.0;
			double ztj=0.0;
			String c="";
			for(NewBill nb:l){
				MaterialParticulars m=new MaterialParticulars();
				m.setStorageInform(s);
				m.setGoodsNumber(nb.getThdh());
				if(!c.contains(nb.getThdh())){
					c+=nb.getThdh()+",";
				}
				m.setMaterialName(nb.getName());
				m.setQuantitiesReceived("0");
				m.setState("未入库");
				m.setVolume(nb.getVoulm());
				m.setRoughWeight(nb.getWeight());
				m.setForecast(nb.getZcl());
				m.setPacking(nb.getLx());
				m.setPackingUnit(nb.getUnit());
				m.setMaterialSpecification(nb.getGg());
				m.setMaterialCode(nb.getCode());
				//m.setWarehouse(nb.getDeop());
				m.setId(UUID.randomUUID().toString().replaceAll("-",""));
				Goods g=goodsService.get(nb.getName().getId());
				String weight=g.getGrossWeight();
				String volm=g.getVolume();
				zmz+=Integer.parseInt(nb.getZcl())*Double.parseDouble(weight);
				ztj+=Integer.parseInt(nb.getZcl())*Double.parseDouble(volm);
				zjs+=Integer.parseInt(nb.getZcl());
				materialParticularsMapper.insert(m);
			}
			s.setDeliveryNumber(c);
			s.setRoughWeight(nf.format(zmz).replaceAll(",",""));
			s.setTotalVolume(nf.format(ztj).replaceAll(",",""));
			s.setForecast(zjs+"");
			storageInformService.save(s);
		}}
		j.setMsg("发车成功");
		return j;
	}
	/**
	 * 批量删除派车单
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatching:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			dispatchingService.delete(dispatchingService.get(id));
		}
		j.setMsg("删除派车单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatching:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Dispatching dispatching, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "派车单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Dispatching> page = dispatchingService.findPage(new Page<Dispatching>(request, response, -1), dispatching);
    		new ExportExcel("派车单", Dispatching.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出派车单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:dispatching:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Dispatching> list = ei.getDataList(Dispatching.class);
			for (Dispatching dispatching : list){
				try{
					dispatchingService.save(dispatching);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条派车单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条派车单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入派车单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/dispatching/?repage";
    }
	
	/**
	 * 下载导入派车单数据模板
	 */
	@RequiresPermissions("tms:dispatching:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "派车单数据导入模板.xlsx";
    		List<Dispatching> list = Lists.newArrayList(); 
    		new ExportExcel("派车单数据", Dispatching.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/dispatching/?repage";
    }

}